package com.lx.framework.weixin.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.lx.framework.core.entity.SysFile;
import com.lx.framework.exception.ServiceException;
import com.lx.framework.service.ISysFileService;
import com.lx.framework.util.FileUtils;
import com.lx.framework.util.JsonUtil;
import com.lx.framework.weixin.config.WeiXinMiniConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sylow
 * @Description 微信小程序
 * @Date: Created in 14:14 2023/8/3
 */
@Component
public class WeiXinMiniService {
    private final static Logger logger = LoggerFactory.getLogger(WeiXinMiniService.class);


    private  final WeiXinMiniConfig weiXinMiniConfig;
    private final WeiXinMpService weiXinMpService;
    private final ISysFileService sysFileService;

    public WeiXinMiniService(WeiXinMiniConfig weiXinMiniConfig, WeiXinMpService weiXinMpService, ISysFileService sysFileService) {
        this.weiXinMiniConfig = weiXinMiniConfig;
        this.weiXinMpService = weiXinMpService;
        this.sysFileService = sysFileService;
    }

    public String getOpenId(String code) {
        String appid = weiXinMiniConfig.getAppid();
        String appSecret = weiXinMiniConfig.getAppSecret();
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appid
                + "&secret=" + appSecret
                + "&js_code=" + code
                +"&grant_type=authorization_code";

        String result = HttpRequest.get(url).execute().body();
        logger.debug("微信小程序登录返回结果:{}", result);
        if (StrUtil.isNotBlank(result)) {
            Map resultMap = JsonUtil.jsonToMap(result);
            if (resultMap.containsKey("openid")) {
                String openId = resultMap.get("openid").toString();
                return openId;
            } else {
                logger.error("获取微信openId失败：{}", result);
            }
        }
        return "";
    }

    public String getMiniQrCode(String scene, String page) {

        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + weiXinMpService.getMiniAccessToken();
        Map<String, Object> params = new HashMap<>();
        params.put("scene", scene);
        if (StrUtil.isNotBlank(page)){
            params.put("page", page);
        }
        //开始获取数据
        byte[] bytes = HttpRequest.post(url).body(JsonUtil.objectToJson(params)).execute().bodyBytes();
        //BufferedInputStream bis = new BufferedInputStream(content);
        MultipartFile file = FileUtils.getMultipartFile("miniQrCode.jpg", bytes);
        try {
            SysFile sysFile = sysFileService.upload(file, "weixin");
            return sysFile.getUrl();
        } catch (IOException e) {
            throw new ServiceException("上传失败", e);
        }

    }


}
